package com.ai.aicodemather.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.ai.aicodemather.ai.model.HtmlCodeResult;
import com.ai.aicodemather.ai.model.MultiFileCodeResult;
import com.ai.aicodemather.constant.AppConstant;
import com.ai.aicodemather.model.enums.CodeGenTypeEnum;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * ai生成内容保存器
 */
@Deprecated
public class CodeFileSaver {
    // 文件保存根目录
    private static final String ROOT_PATH = AppConstant.CODE_OUTPUT_ROOT_DIR;

    /**
     * 保存单个文件的方法
     *
     * @param dirPath
     * @param fileName
     * @param content
     */
    private static void saveSingleFile(String dirPath, String fileName, String content) {
        String filePath = dirPath + "/" + fileName;
        FileUtil.writeString(content, filePath, StandardCharsets.UTF_8);
    }

    /**
     * 创建文件的唯一路径,这个路径下存放代码
     *
     * @param bizType
     * @return
     */
    private static String getUniqueFilePath(String bizType) {
        String filePath = String.format("%s_%s", bizType, IdUtil.getSnowflakeNextId());
        String dirPath = ROOT_PATH + File.separator + filePath;
        FileUtil.mkdir(dirPath);
        return dirPath;
    }

    /**
     * 保存html代码文件
     *
     * @param htmlCode
     * @return
     */
    public static File saveHtmlCodeFile(HtmlCodeResult htmlCode) {
        String filePath = getUniqueFilePath(CodeGenTypeEnum.HTML.getValue());
        saveSingleFile(filePath, "index.html", htmlCode.getHtmlCode());
        return new File(filePath);
    }

    /**
     * 保存多文件代码文件
     *
     * @param multiFileCodeResult
     * @return
     */
    public static File saveMultiFileCodeFile(MultiFileCodeResult multiFileCodeResult) {
        String filePath = getUniqueFilePath(CodeGenTypeEnum.MULTI_FILE.getValue());
        saveSingleFile(filePath, "index.html", multiFileCodeResult.getHtmlCode());
        saveSingleFile(filePath, "style.css", multiFileCodeResult.getCssCode());
        saveSingleFile(filePath, "script.js", multiFileCodeResult.getJsCode());
        return new File(filePath);
    }
}
